package servlet;

import entity.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "LoginServlet",urlPatterns = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
//        System.out.println("jsp获得的username="+username);
        String password = request.getParameter("password");
//        System.out.println("jsp获得的password="+password);

        UserService userservice  = new UserServiceImpl();
        User user = userservice.login(username);
//        System.out.println(user);
        if(user!=null){
//            System.out.println("用户存在！");
            if(user.getUPass().equals(password)){
                System.out.println("密码正确！");
                HttpSession session = request.getSession();
                session.setAttribute("user", user);//jsp获取，判断是否登录
                //如果成功跳转到index.jsp
                response.sendRedirect("index.jsp");
            }else {
                request.getRequestDispatcher("login.jsp").forward(request, response);

            }
        }else{
            System.out.println("error,登陆失败!");
            //设置setAttribute，jsp用
            request.setAttribute("msg", "用户名或者密码错误，请重新登录！");
            //response.sendRedirect("login.jsp");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request,response);
    }
}
